2020IT30
input1 = [[1,3],[2,6],[8,10],[15,18]]
output1 = [[1,6],[8,10],[15,18]]
//Explanation: Since intervals [1,3] and [2,6] overlaps,
//merge them into [1,6].
input2 = [[1,4],[4,5]]
output2 = [[1,5]]
//Explanation: Intervals [1,4] and [4,5] are
//considered overlapping.
input1 = [[1,3],[2,6],[8,10],[15,18]]
output1 = [[1,6],[8,10],[15,18]]
//Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
input2 = [[1,4],[4,5]]
output2 = [[1,5]]
//Explanation: Intervals [1,4] and [4,5] are considered overlapping.
function merge(ary){
result = [] //裝判斷後的結果
for(let i = 1; i < ary.length; i++){
if(ary[i-1][1]-ary[i][0] >= 0){
//藉由子陣列元素相扣判斷是否重疊
result.push([ary[i-1][0],ary[i][1]]) // 重疊就合併
i += 1 // 合併後要往前多跳一個
}else{
// 不重疊就兩個陣列一起塞到 result 中
result.push(ary[i-1])
result.push(ary[i])
}
result = result.filter((arr,index)=>{
// 移除 result 中重疊的元素
if(result.indexOf(arr) == index){
return arr
}
})
}
console.log(result)
return result
}
function expect(a,b){
console.log( JSON.stringify(a) == JSON.stringify(b) )
}
expect(merge(input1),output1)
expect(merge(input2),output2)
今天到此為止,有任何問題請在下方留言或透過email、GitHub聯絡我,感謝閱讀
Daily kitty